#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <vector>
#include <queue>
#include "Task.hpp"
#include "LockGuard.hpp"
const static int N = 5;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

template<class T>
class ThreadPool
{
public:
    ThreadPool(int num = N) : _num(num), _threads(num)
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    void LockQueue()
    {
        pthread_mutex_lock(&_lock);
    }
    void UnLockQueue()
    {
        pthread_mutex_unlock(&_lock);
    }
    void ThreadWait()
    {
        pthread_cond_wait(&_cond, &_lock);
    }
    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    bool isEmpty()
    {
        return _tasks.empty();
    }
    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }

    static void *threadRoutine(void* args)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        
        pthread_detach(pthread_self());
        while(1)
        {
            tp->LockQueue();
            while(tp->isEmpty())
            {
                tp->ThreadWait();
            }
            T t = tp->popTask();         
            tp->UnLockQueue();
            t(); //运行任务
            std::cout << "pthread : " << pthread_self() << " result : " << t.formatRes() << std::endl; 
        }
    }
    void start()
    {
        for(int i = 0; i < _num; i++)
        {
            pthread_create(&_threads[i], nullptr, threadRoutine, this);
        }
    }
    void pushTask(const T& s)
    {
        LockQueue();
        _tasks.push(s);
        ThreadWakeup();   
        UnLockQueue();    
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<pthread_t> _threads;
    int _num;
    std::queue<T> _tasks;
    pthread_mutex_t _lock;
    pthread_cond_t _cond;
};
